<template>
  <div class="dialog-box" style="position: relative">
    <el-row type="flex" justify="space-between" align="middle">
      <span>表格配置</span>
      <el-select
        v-model="formData.filterFields"
        :size="defaultFormItemSize"
        clearable
        filterable
        multiple
        :collapse-tags="true"
        placeholder="请选择过滤字段"
        style="width: 250px"
      >
        <el-option
          v-for="item in dialogParams.tableColumnList"
          :key="item.columnName"
          :label="item.columnName"
          :value="item.columnName"
        />
      </el-select>
    </el-row>
    <el-row style="margin: 16px 0px">
      <el-col :span="24">
        <vxe-table
          ref="table"
          header-cell-class-name="table-header-gray"
          :data="tableData"
          :row-config="{ height: 50, isHover: true, drag: true }"
          :virtual-y-config="{ enabled: true, gt: 20 }"
          height="400px"
        >
          <vxe-column type="seq" width="60px" title="序号" />
          <vxe-column title="字段名称" field="columnName" min-width="150px" />
          <vxe-column title="显示名称" field="columnComment" min-width="150px">
            <template v-slot="scope">
              <el-input v-model="scope.row.columnComment" size="default" style="width: 100%" />
            </template>
          </vxe-column>
          <vxe-column title="绑定字典" field="dictId" min-width="150px">
            <template v-slot="scope">
              <el-select
                v-model="scope.row.dictId"
                size="default"
                filterable
                clearable
                placeholder="请选择字典"
              >
                <el-option
                  v-for="item in dialogParams.dictList"
                  :key="item.dictId"
                  :label="item.dictName"
                  :value="item.dictId"
                />
              </el-select>
            </template>
          </vxe-column>
          <vxe-column title="是否显示" field="isShow" :filters="showOptions" min-width="150px">
            <template #header>
              <span>是否显示</span>
              <el-checkbox
                style="margin-left: 6px"
                v-model="selectAll"
                :indeterminate="isIndeterminate"
                @change="handleSelectAll"
              />
            </template>
            <template v-slot="scope">
              <el-switch v-model="scope.row.isShow" @change="onItemShowChange" />
            </template>
          </vxe-column>
          <vxe-column drag-sort width="60px" title="排序" />
        </vxe-table>
      </el-col>
    </el-row>
    <el-row type="flex" justify="end">
      <el-button :size="defaultFormItemSize" @click="onCancel()">取消</el-button>
      <el-button :size="defaultFormItemSize" type="primary" @click="onSubmit">确定</el-button>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { VxeTable, VxeColumn } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DialogProp } from '@/components/Dialog/types';
import { useThirdParty } from '@/components/thirdParty/hooks';
import { ThirdProps } from '@/components/thirdParty/types';
import { useLayoutStore } from '@/store';
const layoutStore = useLayoutStore();

interface IProps extends ThirdProps {
  data?: ANY_OBJECT;
  tableColumnList?: ANY_OBJECT[];
  dictList?: ANY_OBJECT[];
  // 当使用Dialog.show弹出组件时，须定义该prop属性，以便对dialog进行回调
  dialog?: DialogProp<boolean>;
}

const props = defineProps<IProps>();
const { thirdParams, onCloseThirdDialog } = useThirdParty(props);
const defaultFormItemSize = computed(() => {
  return layoutStore.defaultFormItemSize;
});

const formData = ref({
  filterFields: [],
  tableColumnList: {},
});
const table = ref();
const tableData = ref([]);
const selectAll = ref(false);
const showOptions = ref([
  { value: true, label: '是' },
  { value: false, label: '否' },
]);

const dialogParams = computed(() => {
  return {
    data: props.data || thirdParams.value.data || {},
    tableColumnList: props.tableColumnList || thirdParams.value.tableColumnList || [],
    dictList: props.dictList || thirdParams.value.dictList || [],
  };
});

const isIndeterminate = computed(() => {
  const allSame = tableData.value.every(item => item.isShow === tableData.value[0].isShow);
  return !allSame;
});

const onCancel = () => {
  if (props.dialog) {
    props.dialog.cancel();
  } else {
    // 关闭第三方弹窗
    onCloseThirdDialog(false);
  }
};

const onSubmit = () => {
  formData.value.tableColumnList = {};
  const { fullData } = table.value.getTableData();
  fullData.forEach((item, index) => {
    formData.value.tableColumnList[item.columnName] = {
      columnComment: item.columnComment,
      dictId: item.dictId,
      isShow: item.isShow,
      showOrder: index,
    };
  });
  if (props.dialog) {
    props.dialog.submit(formData.value);
  } else {
    onCloseThirdDialog(true, dialogParams.value.data, formData.value);
  }
};

const handleSelectAll = value => {
  tableData.value.forEach(item => {
    item.isShow = value;
  });
};

const onItemShowChange = () => {
  // 判断tableDta里的isShow是否都一样
  const allSame = tableData.value.every(item => item.isShow === tableData.value[0].isShow);
  if (allSame) {
    selectAll.value = tableData.value[0].isShow;
  }
};

onMounted(() => {
  formData.value.tableColumnList = dialogParams.value.data.tableColumnList || {};
  formData.value.filterFields = dialogParams.value.data.filterFields || [];
  let tempList = dialogParams.value.tableColumnList.map(item => {
    return {
      columnName: item.columnName,
      columnComment: formData.value.tableColumnList[item.columnName]
        ? formData.value.tableColumnList[item.columnName].columnComment
        : item.columnComment,
      dictId: formData.value.tableColumnList[item.columnName]
        ? formData.value.tableColumnList[item.columnName].dictId
        : '',
      isShow: formData.value.tableColumnList[item.columnName]
        ? formData.value.tableColumnList[item.columnName].isShow
        : true,
      showOrder: formData.value.tableColumnList[item.columnName]
        ? formData.value.tableColumnList[item.columnName].showOrder
        : undefined,
    };
  });
  // 按照showOrder排序
  tempList.sort((a, b) => {
    if (a.showOrder === undefined && b.showOrder === undefined) {
      return 0;
    } else if (a.showOrder === undefined) {
      return 1;
    } else if (b.showOrder === undefined) {
      return -1;
    } else {
      return a.showOrder - b.showOrder;
    }
  });
  tableData.value = tempList;
});
</script>
